package ml;

public class BusyFlag {

	protected Thread busyFlag = null;
	
	public synchronized void getBusyFlag(int time)
	{
		System.out.println("Calling getBusyFlag - " + Thread.currentThread().getId());
		while(true)
		{
			if(busyFlag == null){
				busyFlag = Thread.currentThread();
				break;
			}
			try
			{
				Thread.sleep(time);				
			}
			catch(Exception e) {};
		}
		System.out.println("Leaving getBusyFlag - " + Thread.currentThread().getId());
	}
	
	
	public synchronized boolean tryGetBusyFlag() {
		System.out.println("Calling tryGetBusyFlag - " + Thread.currentThread().getId());
		if(busyFlag == null)
		{
			busyFlag = Thread.currentThread();
			return true;
		}
		
		System.out.println("Leaving tryGetBusyFlag - " + Thread.currentThread().getId());
		return false;
	}
	
	
	public synchronized void freeBusyFlag(){
		System.out.println("Calling freeBusyFlag - " + Thread.currentThread().getId());
		if(busyFlag == Thread.currentThread())
		{
			busyFlag = null;
		}
		System.out.println("Leaving freeBusyFlag - " + Thread.currentThread().getId());
	}
	
	
	
}
